import axios from 'axios'

export function getCurrentLocation(successCallback, errorCallback) {
  function commonSuccessHandler(info) {
    const arr = [info.longitude,info.latitude];
    if ( successCallback ) successCallback(arr.join(','))
  }
  function commonCancelHandler(info) {
    var str = "经纬度信息获取失败，请重试或联系管理员:" + JSON.stringify(info);
    alert( str);
    if ( errorCallback ) errorCallback(str)
  }

  if ( process.env.NODE_ENV == 'development' ) {
    successCallback( "112.57348,37.798933" );
    return;
  }
  // 可选配置项
  const locationConfig ={
    type: 'BD09LL',
    useCache:false,
    altitude:false,
    accuracy:false,
    withReGeocode:false
  };
  // 获取当前坐标，然后再定位当前位置
  qm.locationManager.getCurrentPosition( {
    onSuccess:commonSuccessHandler.bind(this),
    onError:commonCancelHandler.bind(this),
    options:locationConfig
  } )
};
export function regeocoderAddress(lnglat, successCallback, errorCallback) {
  const arr = lnglat.split(',')
  const params = {
    coordinateType: 'bd09ll',
    location: [arr[1], arr[0]].join(','),
    output: 'json',
    ApiAuthorization: window._BMAP.apiAuthorization
  }
  axios.get(window._BMAP.webApiBasePath + '/reverse_geocoding/v3', { params })
    .then( res => res.data )
    .then(res => {
      const { status, result } = res
      if (status == 0) {
        const pois = result.pois
        let address =
          pois.length > 0
            ? pois[0].addr
            : result.addressComponent.province +
              result.addressComponent.city +
              result.addressComponent.district +
              result.sematic_description
        if (successCallback) successCallback(address)
      } else {
        console.error('根据经纬度查询地址失败')
        if (errorCallback) errorCallback()
      }
    })
};

export function geometry(acoords, bcoords, type, successCallback, errorCallback) {
  const params = {
    acoords,
    bcoords,
    type,
    output: 'json',
    ApiAuthorization: window._BMAP.apiAuthorization
  }
  axios.get(window._BMAP.webApiBasePath + '/geometry', { params })
    .then( res => res.data )
    .then(res => {
      const { status, results } = res
      if (status == 0) {
        const data = results[0]
        let value =  null;
        if ( params.type == 'contains' ) value = data.flag;
        if ( params.type == 'distance' ) value = data.distance;
        if ( params.type == 'intersects' ) value = data.flag;
        if (successCallback) successCallback(value)
      } else {
        if (errorCallback) errorCallback()
      }
    })
}

function rad(d) {
  return d*Math.PI/180.0;
}

export function getDistance(lnglat1, lnglat2) {
  const EARTH_RADIUS = 6378137; // 地球赤道半径 单位m
  const lng1 = lnglat1.split(',')[0]
  const lat1 = lnglat1.split(',')[1]
  const lng2 = lnglat2.split(',')[0]
  const lat2 = lnglat2.split(',')[1]

  const a = rad(lat1) - rad(lat2);
  const b = rad(lng1) - rad(lng2);
  let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
          + Math.cos(lat1) * Math.cos(lat2)
          * Math.pow(Math.sin(b / 2), 2)));
  s = s * EARTH_RADIUS;

  return Math.floor(s);
}